package com.presto.directo.mvvm.view

import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.activity.result.contract.ActivityResultContracts
import com.presto.directo.base.BaseActivity
import com.presto.directo.databinding.ActivityLoanBinding
import com.presto.directo.entity.ProductEntity
import com.presto.directo.entity.UserCardEntity
import com.presto.directo.mvvm.adapter.CARD_TYPES
import com.presto.directo.net.*
import com.presto.directo.utils.*
import ru.whalemare.sheetmenu.SheetMenu
import java.util.*

class LoanActivity : BaseActivity() {
    override val rootView: View
        get() = binding.root

    private val binding by lazy { ActivityLoanBinding.inflate(layoutInflater) }

    private lateinit var product: ProductEntity
    private var card: UserCardEntity? = null
    private var path: String = ""
    private val amounts = mutableListOf<String>()
    private val deviceInfoUtil by lazy { DeviceInfoUtil(this) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Af.show_loan_confirm_page.track(this)
        card = intent.getSerializableExtra("card") as UserCardEntity?
        path = intent.getStringExtra("path") ?: ""
        start(onNext = {
            showProgress()
            val livingId = ImageUtil.upload(path)
            val map = getHttpMap()
            map["androidId"] = deviceInfoUtil.getAndroidId()
            map["bank_id"] = card?.bank_id ?: ""
            map["device_id"] = deviceInfoUtil.getImei()
            map["ipAddress"] = SPUtil.get("ipAddress", "")
            map["uuid"] = UUID.randomUUID().toString()
            map["livingId"] = livingId
            map["livingIdSuffix"] = "jpg"
            val products = getApiService().getProducts(map.sign(30)).getResult()
            if (products.isNullOrEmpty()) return@start
            Af.success_get_amounts.track(this)
            product = products.first()
            product.let {
                binding.tvDuration.text = it.duration.toString().appendDayUnit()
                val step = (it.maxAmount - it.minAmount) / 100
                for (i in 0..step) {
                    amounts.add((it.minAmount + i * 100).toString())
                }
                if (amounts.isNotEmpty()) {
                    show(amounts.last())
                }
            }
        }, onComplete = {
            dismissProgress()
        })
        card?.let {
            binding.tvType.text = if (it.card_type == "1") CARD_TYPES[0] else CARD_TYPES[1]
            binding.tvBank.text = it.bank_code
            binding.tvCardNo.text = it.card_no
        }

    }

    override fun initEvent() {
        binding.tvAmount.setOnClickListener {
            SheetMenu(
                actions = amounts,
                onClick = {
                    show(it.title.toString())
                },
                layoutProvider = MyLayoutProvider()
            ).show(this)
        }
        binding.tvReplace.setOnClickListener {
            val intent = Intent(this, CardListActivity::class.java)
            intent.putExtra("fromConfirm", true)
            intent.putExtra("showIndicator", false)
            launcher.launch(intent)
        }
        binding.btnEdit.setOnClickListener {
            startActivity(Intent(this, InfoAddressActivity::class.java))
            finish()
        }
        binding.cbAgree.setOnCheckedChangeListener { buttonView, isChecked -> updateBtn() }
        binding.tvContract.setOnClickListener {
            val map = mutableMapOf<String, String>()
            map["user_id"] = UserUtil.getUserId()
            map["bank_id"] = card?.bank_id ?: ""
            map["productId"] = if (this::product.isInitialized) product.productId else ""
            map["amount"] = binding.tvAmount.text.toString().replace("$", "")
            val intent = Intent(this, WebActivity::class.java)
            intent.putExtra("title", "Contrato de préstamo")
            intent.putExtra("url", ApiService.URL_CONTRACT + map.toUrl())
            startActivity(intent)
        }
        binding.btnNext.setOnClickListener {
            if (card == null) {
                binding.tvReplace.performClick()
                return@setOnClickListener
            }
            if (binding.tvAmount.text.isEmpty()) {
                toast("Seleccionar el monto de préstamo")
                return@setOnClickListener
            }
            Af.click_loan_confirm.track(this)
            start(onNext = {
                showProgress()
                val map = getHttpMap()
                map["product_id"] = if (this::product.isInitialized) product.productId else ""
                map["amount"] = binding.tvAmount.text.toString().replace("$", "")
                getApiService().loan(map.sign(28)).getResultOrNull()
                Af.success_loan_confirm.track(this)
                finish()
            }, onComplete = {
                dismissProgress()
            })
        }
    }

    private val launcher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
        if (it.resultCode != RESULT_OK) return@registerForActivityResult
        card = it.data?.getSerializableExtra("card") as UserCardEntity?
        card?.let {
            binding.tvType.text = if (it.card_type == "1") CARD_TYPES[0] else CARD_TYPES[1]
            binding.tvBank.text = it.bank_code
            binding.tvCardNo.text = it.card_no
        }
    }

    private fun show(item: String) {
        if (!this::product.isInitialized) return
        val amount = item.toDouble()
        binding.tvActualAmount.text = (amount.toBigDecimal() * (1.0.toBigDecimal() - product.feeRate.toBigDecimal())).stripTrailingZeros().toPlainString().appendAmountUnit()
        binding.tvAmount.text = item.appendAmountUnit()
        binding.tvRepayAmount.text = (amount.toBigDecimal() + amount.toBigDecimal() * product.intervalRate.toBigDecimal() * product.duration.toBigDecimal() * (1.toDouble().toBigDecimal() + product.taxProportion.toBigDecimal())).stripTrailingZeros().toPlainString().appendAmountUnit()
        binding.tvDayInterest.text = (amount.toBigDecimal() * product.intervalRate.toBigDecimal()).stripTrailingZeros().toPlainString().appendAmountUnit()
        binding.tvHandFee.text = (amount.toBigDecimal() * product.feeRate.toBigDecimal()).stripTrailingZeros().toPlainString().appendAmountUnit()
        binding.tvRepayTime.text = (System.currentTimeMillis() + product.duration * 24 * 60 * 60 * 1000L).formatTime()
    }

    override fun updateBtn() {
        binding.btnNext.isEnabled = binding.cbAgree.isChecked
    }
}